package api

import (
	"context"
	"encoding/json"
	"fmt"
	"gitee.com/g-qs/gin-vue-admin/server/global"
	"gitee.com/g-qs/gin-vue-admin/server/model/common/response"
	"gitee.com/g-qs/gin-vue-admin/server/plugin/sms/model"
	"gitee.com/g-qs/gin-vue-admin/server/plugin/sms/service"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"math/rand"
	"strings"
	"time"
)

type AliSmsApi struct{}

// @Tags System
// @Summary 发送（阿里）短信
// @Security ApiKeyAuth
// @Produce  application/json
// @Success 200 {string} string "{"success":true,"data":{},"msg":"发送成功"}"
// @Router /aliSms/sendAliSms[post]

//var ctx = context.Background()

func (s *AliSmsApi) SendAliSms(c *gin.Context) {
	var ali model.AliModel
	_ = c.ShouldBindJSON(&ali)
	randomNumStr := generateCode()
	var Tem model.TemplateParam
	Tem.Code = randomNumStr
	str, _ := json.Marshal(Tem)
	phone := strings.Join(ali.Phones, "")
	ip := c.ClientIP()
	writeSmsRedis(phone, Tem.Code, ip)
	if err := service.ServiceGroupApp.SendAliSms(ali.Phones, string(str)); err != nil {
		global.GVA_LOG.Error("发送失败!", zap.Error(err))
		response.Result(-101, "", "发送失败", c)
	} else {
		response.Result(200, "", "发送成功", c)
	}
}

func generateCode() string {
	// 生成随机的 6 位数验证码
	return fmt.Sprintf("%06d", rand.Intn(999999))
}

func writeSmsRedis(phone, code, ip string) {
	// 以 Sms:Phone:Code: + 手机号为 key，将验证码存储到 Redis 中
	err := global.GVA_REDIS.Set(context.Background(), "Sms:Phone:Code:"+phone, code, time.Minute*5).Err()
	if err != nil {
		panic(err)
	}
	// 以 Sms:Phone:Ip: + IP 地址为 key，将请求时间存储到 Redis 中
	err = global.GVA_REDIS.Set(context.Background(), "Sms:Phone:Ip:"+ip, time.Now().Unix(), time.Minute*5).Err()
	if err != nil {
		panic(err)
	}
	// 以 Sms:Phone:Time: + 手机号为 key，将请求时间存储到 Redis 中
	err = global.GVA_REDIS.Set(context.Background(), "Sms:Phone:Time:"+phone, time.Now().Unix(), time.Minute*5).Err()
	if err != nil {
		panic(err)
	}
}
